package com.scrabbleMaster;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class Dictionary {
	public Set<String> words = new HashSet<String>();
	
	public Dictionary() {
	}

	public Dictionary(Collection<String> words) {
		for (String word : words) {
			this.add(word);
		}
	}

	public void add(String word) {
		this.words.add(word.toUpperCase());
	}

	public boolean exists(String word) {	
		return this.words.contains(word.toUpperCase());
	}
	
	public static Collection<String> readWordsFromFile(File file) throws IOException {
		String line;
		Collection<String> words = new HashSet<String>();
		FileInputStream fis = new FileInputStream(file);
		BufferedReader br = new BufferedReader(new InputStreamReader(fis));
		while ((line = br.readLine()) != null) {
		    words.add(line);
		}
		br.close();
		br = null;
		fis = null;
		return words;
	}

	public static Dictionary fromResource() throws Exception {
		URL url = ClassLoader.getSystemResource("dictionary.es");
		File file = new File( url.toURI() );
		return new Dictionary(Dictionary.readWordsFromFile(file));
	}

	public Collection<String> filterValidWords(Collection<String> shuffle) {
		Collection<String> result = new HashSet<String>();
		for (String string : shuffle) {
			if (this.exists(string))
				result.add(string);
		}
		return result;
	}

}
